package com.soyotec.algorithm.algorithm.process;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class RandomAccessFileWriter extends Writer {
    private RandomAccessFile raf;
    public RandomAccessFileWriter(RandomAccessFile raf){
        this.raf=raf;
    }
    @Override
    public synchronized void write(char[] cbuf, int off, int len) throws IOException {

        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(cbuf.length);
        cb.put(cbuf);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
        String content=new String(bb.array());
        if(content.contains("#{\"code\":2}")) {//一轮迭代开始需要刷新数据
            raf.setLength(0);
        }
        raf.write(getBytes(cbuf),off,len);
    }
    public synchronized static byte[] getBytes(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
//        System.out.println("----------------------------------------RandomAccessFileWriter byte:"+new String(bb.array()));
        return bb.array();
    }
    @Override
    public synchronized void flush() throws IOException {

    }

    @Override
    public synchronized void close() throws IOException {
        raf.close();
    }




}
